
const medica = require('../../utils/medica.common.js')
import daysbefore from '../../../plugin/daysbefore';
import api from '../../../api/index'
const md5 = require("../../utils/md5");
var dayjs = require('dayjs')
import * as echarts from '../../../components/ec-canvas/echarts';
//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;
var charthistory = null;
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bindDeviceId: null,
    devicelist: [],
    showDevice: false,
    actions: [],
    bindDevice: [],
    saveDevice: {},
    showDialog: false,
    bindDeviceTextInfo: '',
    loading: false,
    currentDevice: null,
    timer: null,
    bleAvaible: true,
    saveDataList: [],
    summaryList: [],
    reportData: {},
    startDate: null,
    endDate: null,
    scale: 0,
    shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/shuimian.jpg',
    fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
    allduration: '--',
    getstartTime: '--',
    deepsleepratio: '--',
    midddlesleepratio: '--',
    shallowsleepratio: '--',
    linedata: null,
    show: false,
    ec: {
      // 初始化图表
      onInit: (canvas, width, height) => {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        return chart;
      }
    },
    linedatahistory: null,
    historyshow: false,
    echistory: {
      // 初始化图表
      onInit: (canvas, width, height) => {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        charthistory = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(charthistory);
        return charthistory;
      }
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    console.log(options);
    const { titlename } = options
    console.log(titlename);
    wx.setNavigationBarTitle({
      title: titlename // 设置页面标题
    })
    this.geticon()
    this.getSetTime()
    this.openBluetoothAdapter()
    // this.onBluetoothAdapterStateChange()
    this.getloadlist()
    this.gethistrorylist()
  },
  gethistrorylist() {
    api
      .post('/api/hxhealth/exams/records', {
        data: {
          begindate: daysbefore.daysbefore(365),
          enddate: formatTime2(),
          everyday: true,
          itemcode: 'XYZBXY001041'
        }
      })
      .then((res) => {
        // console.log(res);
        console.log('----历史数据----', res);
        if (res.length > 0) {
          const jsonData = res;
          // 提取数据的数组
          const values = [];
          const times = [];
          // 遍历 body 数组
          jsonData.forEach((entry) => {
            // 遍历 devices 数组
            entry.devices.forEach((device) => {
              console.log(device);
              // 找到 code 为 "XYZBXY001041" 的项
              const item = device.items.find((item) => item.code === 'XYZBXY001041');

              // 如果找到了，将 value 和 time 添加到相应的数组中
              if (item) {
                console.log(item);
                values.push(Number(item.value)); // 将值转换为数字类型
                times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
              }
            });
          });
          const linedatahistory = {
            values,
            times
          };
          console.log(linedatahistory);
          console.log(res[0].time);
          this.setData({
            history:res,
            linedatahistory
          });
          // 模拟获取接口数据
          setTimeout(() => {
            this.getEchartDatahistory(linedatahistory);
          }, 1000);
        }
      });
  },
  getEchartDatahistory(linedatahistory) {
    console.log(linedatahistory, 'huizhi----2222------');
    const icon = this.data.base64Img
    seriesDataArr = [
      {
        name: '',
        type: 'line',
        stack: 'Total',
        smooth: true,
        data: linedatahistory.values,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(30, 144, 255, 0)' // 起始颜色
            }, {
              offset: 1,
              color: 'rgba(30, 144, 255, 0.8)' // 结束颜色
            }]
          }
        }
      }
    ];
    timeArr = linedatahistory.times;
    this.runColumncCanvahistory();
  },
    // 绘制历史记录图表
    runColumncCanvahistory() {
      console.log(timeArr, '绘制历史记录图表------------------------------');
      console.log(seriesDataArr, '绘制历史记录图表------------------------------');
      var option = {
        title: {
          // text: '次/分',
          textStyle: {
            fontSize: 10,
            color: '#666666'
          }
        },
        color: ['#37A2DA'],
        legend: {
          data: ['绘制历史记录图表'],
          icon: 'circle',
          left: 0,
          itemWidth: 9,
          // itemStyle: {
          //     color: '#5BBF70'
          // },
          textStyle: {
            color: '#333333',
            fontSize: 20
          }
        },
        grid: {
          left: '0%',
          right: '3%',
          bottom: '15%',
          top: '13%',
          containLabel: true,
          show: true
        },
        tooltip: {
          show: true,
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false, // 隐藏X轴轴线
          },
          axisTick: {
            show: false, // 隐藏X轴刻度线
          },
          position: 'top',
          boundaryGap: true,
          data: timeArr,
          axisLabel: {
            rotate: 0, //倾斜度 -90 至 90 默认为0
            fontSize: 16, // 文字大小
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            },
          },
          splitNumber: 3,
          inverse: false, // 倒序显示
          axisLabel: {
            fontSize: 16, // 文字大小
          }
        },
        series: seriesDataArr
      };
      console.log(charthistory, 'charthistory')
      //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
      if (charthistory) {
        charthistory.setOption(option);
        this.setData({
          historyshow: true
        });
      }
    },
  // 初始化蓝牙
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        this.setData({
          bleAvaible: true
        })
        console.log(res, '蓝牙初始化成功')
      },
      fail: (error) => {
        console.log(error, '蓝牙初始化失败')
        this.setData({
          bleAvaible: false
        })
        this.bluetoothInitFailed()
      },
      complete: () => {
        this.get()
      }
    })
  },
  // 监听蓝牙开关状态
  onBluetoothAdapterStateChange() {
    console.log('onBluetoothAdapterStateChange开始')
    medica.b501tBleApi.onBluetoothAdapterStateChange((available) => {
      // available: true 蓝牙打开, false 蓝牙关闭
      console.log('onBluetoothAdapterStateChange结束', available);
      if (available) {
        this.setData({
          bleAvaible: true
        })
        this.get()
        // if (this.data.saveDevice.name) {
        //   this.onBind()
        // } else {
        //   // 蓝牙打开自动搜索
        //   this.goBindEq()
        // }
      } else {
        this.setData({
          bleAvaible: false
        })
      }
    });
  },
  // 监听蓝牙链接状态
  onBLEConnectionStateChange(deviceId) {
    medica.b501tBleApi.onBLEConnectionStateChange(deviceId, (connected) => {
      console.log('onBLEConnectionStateChange', connected);
    })
  },
  bluetoothInitFailed() {
    this.setData({
      bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
    })
    this.setData({
      showDialog: true
    })
  },
  onCancel() {
    this.setData({
      showDialog: false,
    })
  },
  // 链接设备
  goBindEq() {
    if (!this.data.bleAvaible) {
      wx.showToast({
        title: '蓝牙初始化失败',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.setData({
      bindDeviceTextInfo: '正在搜索蓝牙设备'
    })
    this.setData({
      showDialog: true
    })
    this.onScan()
    // this.createTimeInter()
  },
  onScan() {
    medica.b501tBleApi.scanBleDevices(15000, false, (device) => {
      if (device.name === '0994' || device.localName === '0994') {
        console.log('找到了设备', device)
        this.setData({
          currentDevice: device
        })
        const actions = [
          { name: device.name, subname: device.deviceId, deviceId: device.deviceId, mac: device.mac },
        ]
        this.setData({
          showDialog: false,
          actions: actions
        })
      }
    })
  },
  // 获取设置的监测时间
  async getSetTime() {
    const res = await api.post('/api/user/storage/get', {
      data: {
        'key': 'setUptime'
      }
    })
    if (res[0].value !== "") {
      const listData = JSON.parse(res[0].value)[0]
      console.log(listData);
      console.log(listData.startDate);
      this.setData({
        startDate: listData.startDate,
        endDate: listData.endDate,
      });
    }
  },
  async get() {
    this.setData({
      bindDevice: []
    })
    try {
      this.setData({
        loading: true
      })
      const res = await api.post('/api/user/storage/get', {
        data: {
          'key': 'devicelist'
        }
      })
      if (res[0].value) {
        var array = JSON.parse(res[0].value)
        const listValue = array.filter(item => item.name === 'sleep')
        console.log(listValue,'listValuelistValue')
        if (listValue.length > 0) { // 如果绑定的有设备，直接连接
          if (listValue[0].devicelist.length > 0) {
            this.setData({
              saveDevice: listValue[0].devicelist[0]
            })
            console.log(this.data.bleAvaible,'this.data.bleAvaible1')
            if (this.data.bleAvaible) { // 如果蓝牙已打开，直接链接设备
              this.onBind()
            }
          }
        }
      }
      this.setData({
        loading: false
      })
    } catch (e) {
      console.log('get->', e)
      return null
    }
  },
  goSetTime() {
    wx.navigateTo({ url: '/sleepManagement/pages/setuptime/index' });
  },
  onClose() {
    this.setData({ showDevice: false });
  },
  onSelect(event) {
    console.log(event, 'event.detail')
    this.setData({
      saveDevice: event
    })
    const device = this.data.bindDevice.find(item => {
      return item.name === this.data.saveDevice.name
    })
    let saveDataList = []
    // 如果绑定的有该设备
    if (device) {
      wx.showToast({
        title: '该设备已绑定',
        icon: 'none',
        duration: 3000
      })
    } else {
      const bindDevice = { name: this.data.saveDevice.name, deviceId: this.data.saveDevice.deviceId, mac: this.data.saveDevice.mac }
      saveDataList = this.data.bindDevice.concat(bindDevice)
      this.setData({
        saveDataList: saveDataList
      })
      this.onBind()
    }
  },
  // 绑定设备
  onBind() {
    console.warn(this.data.saveDevice, '--------------开始绑定设备')
    this.setData({
      bindDeviceTextInfo: '正在绑定设备'
    })
    this.setData({
      showDialog: true
    })
    medica.b501tBleApi.connectDevice(this.data.saveDevice.deviceId, 20000, (ret, retDeviceId) => {
      console.log(ret, retDeviceId, '绑定结束')
      if (ret) {
        this.setData({
          bindDeviceTextInfo: '设备绑定成功'
        })
        this.onBLEConnectionStateChange(this.data.saveDevice.deviceId)
        setTimeout(() => {
          this.setData({
            showDialog: false,
          })
        }, 500);
        this.setUserId()
        const startDate = this.data.startDate
        const stList = startDate.split(':')
        const endDate = this.data.endDate
        const duration = this.calculateDuration(startDate, endDate);
        // this.setMonitorTime(Number(stList[0]), Number(stList[1]), duration)
        setTimeout(() => {
          this.getHistoryDataSummary()
        }, 3000)
      } else {
        this.setData({
          bindDeviceTextInfo: '设备绑定失败'
        })
        setTimeout(() => {
          this.setData({
            showDialog: false,
          })
        }, 500);
      }
    })
  },
  getHistoryData() {
    wx.showToast({
      icon: 'none',
      title: '正在获取数据'
    });
    this.getHistoryDataSummary()
  },
  closeConnect() {
    medica.b501tBleApi.closeConnection()
  },
  getloadlist() {
    console.log('2222');
    // 整体列表查询
    api.post('/api/exams/lastvalues', {
      data: {
        devkind: 'ECG',
        devmode: '',
        itemcode: '',
        typecode: '',
        unionuser: true
      }
    }).then((res) => {
      // console.log(res);
      console.log('----res----', res[0])
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  getUserId() {
    medica.b501tBleApi.getUserId({
      handler: function (code, res) {
        console.log('getUserID', code, res);
      }
    })
  },
  setUserId() {
    const userInfo = wx.getStorageSync('userInfo')
    console.log(userInfo.id, 'userId------储存-------------------')
    const userId = Number(userInfo.id)
    medica.b501tBleApi.setUserID({
      userId: userId,
      handler: function (res) {
        console.log('储存结果');
        console.log('setUserID', res);
      }
    })
  },
  calculateDuration(start, end) {
    const [startHour, startMinute] = start.split(':').map(Number);
    const [endHour, endMinute] = end.split(':').map(Number);
    let duration = 0;
    if (startHour < endHour) {
      duration = (endHour - startHour) * 60 + (endMinute - startMinute);
    } else if (startHour === endHour) {
      duration = endMinute - startMinute;
    } else {
      duration = (24 - startHour + endHour) * 60 + (endMinute - startMinute);
    }
    return Math.abs(duration);
  },
  // 设置监测时间
  setMonitorTime(hour, minute, duration) {
    console.log(duration, 'duration')
    medica.b501tBleApi.setMonitorTime({
      hour: hour,
      minute: minute,
      duration: duration,
      week: 127,
      handler: function (code, res) {
        console.log("设置开始监测时间的结果status:" + code, res)
      }
    })
  },
  // 获取当前睡眠状态
  getSleepState() {
    medica.b501tBleApi.getSleepState({
      timeout: 10000,
      handler: function (code, data) {
        console.log("获取睡眠状态结果code:", code, data)
      }
    })
  },
  // 获取采集状态
  getMonitorState() {
    medica.b501tBleApi.getMonitorState({
      timeout: 10000,
      handler: function (code, data) {
        console.log("获取采集状态结果code:", code, data)
      }
    })
  },
  // 获取监测时间
  getMonitorTime() {
    medica.b501tBleApi.getMonitorTime({
      timeout: 10000,
      handler: function (code, data) {
        console.log("获取监测时间结果code:", code, data)
        if (data.duration == 0) {
          this.setMonitorTime(10, 0, 450)
        }
      }
    })
  },
  // 获取睡眠扣监测历史数据
  getHistoryDataSummary() {
    console.log('获取历史数据了')
    const startTime = dayjs('2020-01-19 02:40:44').unix()
    const endTime = dayjs().unix()
    console.log(startTime, 'startTime')
    console.log( endTime, 'endTime')
    medica.b501tBleApi.getHistoryDataSummary({
      startTime: startTime,
      endTime: endTime,
      timeout: 20000,
      handler: (code, res) => {
        console.log('code: ', code, '概要信息为', res)
        if (code == 0 && res.count > 0) {
          console.log(res.count - 1);
          const data = [res.dataList[res.count - 1]]
          this.setData({
            summaryList: data
          })
          console.log(JSON.stringify(data), 'EEEEEEE')
          this.downloadHistoryData()
        }
      }
    })
  },
  // 
  downloadHistoryData() {
    console.log('下载原始数据1111', this.data.summaryList)
    // const startTime = dayjs('2024-02-19 02:40:44').unix()
    const startTime = this.data.summaryList[0].startTime
    const endTime = dayjs().unix()
    // const endTime = dayjs('2024-02-19 07:00:00').unix()
    console.log(endTime, '下载原始数据endTime')
    medica.b501tBleApi.downloadHistoryData({
      startTime,
      endTime: endTime,
      evDataEnable: true,
      timeout: 25000,
      summaryHandle: (count) => {
        console.log(count, '总共报告条数');
      },
      everyReportHandle: (index, count, report) => {
        console.log(count, report, 'report');
      },
      completion: (status, reports) => {
        console.log(status, reports, 'CCCCCCC')
        const report = reports[0]
        this.setData({
          reportData: report
        })
        console.log(this.data.reportData, 'dddd-----------------------------------------')
        console.log(this.data.reportData.feature1, 'feature1-----------------------------------------', this.data.reportData.feature1.length);
        console.log(this.data.reportData.feature2, 'feature2-----------------------------------------');
        console.log(this.data.reportData.feature2.length);
        console.log(this.data.reportData.flag, 'flag-----------------------------------------');
        this.getTestData()
      }
    })
  },
  getTestData() {
    const appKey = '60IDZO3fUFkg'; // 请替换为您申请到的appKey
    const timestamp = dayjs().unix();
    console.log(appKey, 'appKey');
    console.log(timestamp, '当前时间戳');
    const strToEncrypt = appKey + timestamp;
    console.log(strToEncrypt, 'appKey + timestamp');
    const md5Encrypt = md5.md5(strToEncrypt, 32);
    console.log(md5Encrypt, '计算MD5加密结果');
    console.log(this.data.reportData.summary.startTime, '报告开始时间');
    // wx.request({
    //   url: 'http://120.24.68.136:9093/medica/third/sleepDot',
    //   method: 'POST',
    //   data: {
    //     token: {
    //       appId: '57083',
    //       secureKey: md5Encrypt,
    //       timeStamp: timestamp
    //     },
    //     "datas": [
    //       {
    //         feature01: this.data.reportData.feature1,
    //         feature02: this.data.reportData.feature2,
    //         flagstatus: this.data.reportData.flag,
    //         "gender": 1,
    //         "startTime": this.data.reportData.summary.startTime,
    //         "timezone": 28800
    //       }
    //     ]
    //   },
    //   success: (res) => {
    //     console.log(res, 'AAA');
    //     const value = res.data.data
    //   },
    //   fail: (error) => {
    //     console.log(error, 'error');
    //   }
    // })
    console.log('打印打印-----------feature1长度------------------', this.data.reportData.feature1.length);
    console.log(JSON.stringify(this.data.reportData.feature1))
    console.log(this.data.reportData.feature2.length);
    wx.request({
      url: 'http://120.24.68.136:9093/medica/third/sleepDot',
      method: 'POST',
      // },
      data: {
        token: {
          appId: '57083',
          secureKey: md5Encrypt,
          timeStamp: timestamp
        },
        //   token: {
        //   appId: 'NyDrvxpXSDxDt8p6',
        //   secureKey: 'dbcf34711af29f0e98fa9f6fefa94b01',
        //   timeStamp: timestamp
        // },
        "datas": [
          {
            feature01: this.data.reportData.feature1,
            feature02: this.data.reportData.feature2,
            flagstatus: this.data.reportData.flag,
            "gender": 2,
            "startTime": this.data.reportData.summary.startTime,
            "timezone": 28800
          }
        ]
      },
      success: (res) => {
        console.log(res, 'FFF-------');
        let value = null
        let scaleresult = null
        if (res.data.data.length > 0) {
          value = res.data.data[0].historyAnalysis
          console.log(value);
          if (value.scale) {
            if (value.scale < 60) {
              scaleresult = '太差了'
            }
            if (value.scale6 >= 60 && value.scale6 < 80) {
              scaleresult = '一般'
            }
            if (value.scale6 >= 80 && value.scale6 < 90) {
              scaleresult = '不错'
            }
            if (value.scale6 >= 90 && value.scale6 <= 100) {
              scaleresult = '好极了'
            }
          }
          console.log(value.startTime);
          // 创建Date对象并传入时间戳
          const date = new Date(value.startTime * 1000); // 注意要将时间戳乘以1000，因为JavaScript中的时间戳是以毫秒为单位的
          // 获取年份、月份、日期、小时、分钟、秒钟
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          const hour = date.getHours().toString().padStart(2, '0');
          const minute = date.getMinutes().toString().padStart(2, '0');
          const second = date.getSeconds().toString().padStart(2, '0');
          const timeString = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
          console.log(value.scale);
          var duration = value.duration; // 或者 var duration = 20;
          var hours = Math.floor(duration / 60); // 获取小时数
          var minutes = duration % 60; // 获取分钟数
          var result = "";
          if (hours > 0) {
            result += hours + "小时 ";
          }
          result += minutes + "分钟";
          this.setData({
            datalist: value,
            scale: value.scale,
            scaleresult: scaleresult,
            getstartTime: timeString,
            allduration: result,
            deepsleepratio: value.mdDeepSleepPerc,
            midddlesleepratio: value.mdRemSleepPerc,
            shallowsleepratio: value.mdLightSleepPerc,
            sleepCurve: JSON.parse(value.sleepCurve)
          })
          this.formatsleepCurve()
          var that = this;
          that.canvasRing = that.selectComponent("#canvasRing");
          that.canvasRing.showCanvasRing();
          if(this.data.getstartTime !==this.data.history[this.data.history.length-1].time) {
            console.log('时间不同需要保存---------00-------',this.data.getstartTime,this.data.history[this.data.history.length-1].time);
            console.log(this.data.getstartTime)
              let date1 = (new Date(this.data.getstartTime)).getTime()
              let date2 = (new Date(this.data.history[this.data.history.length-1].time)).getTime();
              console.log('date1',date1);
              console.log('date2',date2);
              if (date1 < date2) {
                console.log(`最新记录 在 历史记录 之前`);
              } else if (date1 > date2) {
                console.log(`最新记录 在 历史记录 之后`);
                this.savedevices()
              } else {
                console.log(`最新记录 和 历史记录 是相同时间`);
              }
          } else {
            console.log('时间相同无需保存--------11--------',this.data.getstartTime);
          }
        } else {
          console.log('最近一条数据不可绘制----------------');
        }
      },
      fail: (error) => {
        console.log(error, 'error');
      }
    })
  },
  savedevices() {
    let data = {
			name: '睡眠监测',
			time: formatTime(),
			typecode: 'laikangwriststrap',
			typename: '睡眠监测',
			devices: [
				{
					name: '睡眠评分',
					kind: 'laikangwriststrap',
					items: [
						{
              time:this.data.getstartTime,
							code: 'XYZBXY001041',
							checkDate: null,
							level: null,
							value: this.data.scale,
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			
	},
  formatTime: function (time) {
    let year = time.getFullYear();
    let month = String(time.getMonth() + 1).padStart(2, '0');
    let day = String(time.getDate()).padStart(2, '0');
    let hour = String(time.getHours()).padStart(2, '0');
    let minute = String(time.getMinutes()).padStart(2, '0');
    let second = String(time.getSeconds()).padStart(2, '0');
    let formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    return formattedTime.slice(11, 16);
  },
  formatsleepCurve() {
    var length = this.data.sleepCurve.length;
    var startTime = new Date(this.data.getstartTime);
    let timeList = [];
    // 找到第一个大于等于1的元素的下标
    let firstGreaterIndex = this.data.sleepCurve.findIndex((value) => value >= 1);
    for (let i = 0; i < length; i++) {
      let time = new Date(startTime.getTime() + i * 60000);
      let formattedTime = this.formatTime(time)
      timeList.push(formattedTime);
    }
    console.log(timeList, 'timeList');
    console.log(this.data.sleepCurve, 'sleepCurve');
    let percentage = (firstGreaterIndex / length) * 100;
    console.log('当前下标占整个数组数量的位置百分比：', percentage);
    this.setData({
      percentage
    })
    this.drawcanvas(this.data.sleepCurve, timeList)
  },
  drawcanvas(values, times) {
    const linedata = {
      values,
      times
    };
    this.setData({
      linedata
    })
    // 模拟获取接口数据
    setTimeout(() => {
      this.getEchartData(linedata);
    }, 1000);
  },
  geticon() {
    wx.request({
      url: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/sleepManagement/moon.jpg',
      responseType: 'arraybuffer',
      success: res => {
        const base64Img = wx.arrayBufferToBase64(res.data);
        this.setData({
          base64Img: 'data:image/png;base64,' + base64Img
        })
        // this.getTestData()
        // this.getHistoryDataSummary()
      },
      fail: err => {
        console.error('获取图片失败', err);
      }
    });
  },
  getEchartData(linedata) {
    console.log(linedata, 'huizhi----2222------');
    const icon = this.data.base64Img
    seriesDataArr = [
      {
        name: '',
        type: 'line',
        stack: 'Total',
        smooth: true,
        data: linedata.values,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(30, 144, 255, 0)' // 起始颜色
            }, {
              offset: 1,
              color: 'rgba(30, 144, 255, 0.8)' // 结束颜色
            }]
          }
        }
      }
    ];
    timeArr = linedata.times;
    this.runColumncCanva();
  },
  // 绘制图表
  runColumncCanva() {
    console.log(timeArr, 'huizhi-----3333-----');
    console.log(seriesDataArr, 'huizhi-----3333-----');

    var option = {
      title: {
        // text: '次/分',
        textStyle: {
          fontSize: 10,
          color: '#666666'
        }
      },
      color: ['#37A2DA'],
      legend: {
        data: ['睡眠监测变化趋势'],
        icon: 'circle',
        left: 0,
        itemWidth: 9,
        // itemStyle: {
        //     color: '#5BBF70'
        // },
        textStyle: {
          color: '#333333',
          fontSize: 20
        }
      },
      grid: {
        left: '0%',
        right: '3%',
        bottom: '15%',
        top: '13%',
        containLabel: true,
        show: true
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        formatter: (params) => {
          let str = `${params[0].name}`
          params.forEach((item) => {
            let value = ''
            if (item.value === 0) {
              value = '清醒'
            } else if (item.value <= 1 && item.value > 0) {
              value = '浅睡'
            } else if (item.value <= 2 && item.value > 1) {
              value = '中睡'
            } else if (item.value <= 3 && item.value > 2) {
              value = '深睡'
            }
            str += `-${value}`
          })
          return str
        },
      },
      xAxis: {
        type: 'category',
        axisLine: {
          show: false, // 隐藏X轴轴线
        },
        axisTick: {
          show: false, // 隐藏X轴刻度线
        },
        position: 'top',
        boundaryGap: true,
        data: timeArr,
        axisLabel: {
          rotate: 0, //倾斜度 -90 至 90 默认为0
          fontSize: 16, // 文字大小
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          },
        },
        min: -1,
        max: 3,
        splitNumber: 3,
        inverse: true, // 倒序显示
        axisLabel: {
          formatter(value, index) {
            if (value === 0) {
              return '清醒'
            } else if (value <= 1 && value > 0) {
              return '浅睡'
            } else if (value <= 2 && value > 1) {
              return '中睡'
            } else if (value <= 3 && value > 2) {
              return '深睡'
            }
          },
          fontSize: 16, // 文字大小
        }
      },
      graphic: {
        elements: [{
          type: 'image',
          style: {
            image: this.data.base64Img,
            width: 36,
            height: 35
          },
          left: this.data.percentage + '%',
          top: '80'
        }]
      },
      series: seriesDataArr
    };
    console.log(chart, 'chart')
    //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
    if (chart) {
      chart.setOption(option);
      this.setData({
        show: true
      });
    }
  },
  // 去链接设备
  goBindEq2() {
    wx.navigateTo({
      url: '/sleepManagement/pages/device/index'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})